<template>
  <div class="detail">
    <detail-nav-bar class="detail-nav" @titleClick="titleClick" ref="nav" />
    <!-- 加上冒号才是真正的 number 类型，否则当成字符串处理 -->
    <scroll
      class="content"
      ref="scroll"
      @scroll="contentScroll"
      :probe-type="3"
    >
      <!-- 属性：topImages 传入值：top-images
             html 解析属性的时候，是不区分大小写的
             但是不一样，所以这里要注意 -->
      <detail-swiper :top-images="topImages" />
      <detail-base-info :goods="goods" />
      <detail-shop-info :shop="shop" />
      <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad" />
      <detail-param-info :param-info="paramInfo" ref="param" />
      <detail-comment-info :comment-info="commentInfo" ref="comment" />
      <goods-list :goods="recommends" ref="recommend" />
    </scroll>
    <detail-bottom-bar @addToCart="addToCart" />
    <back-top @click.native="backClick" v-show="isShowBackTop" />
  </div>
</template>

<script>
import DetailNavBar from "./childCmps/DetailNavBar";
import DetailSwiper from "./childCmps/DetailSwiper";
import DetailBaseInfo from "./childCmps/DetailBaseInfo.vue";
import DetailShopInfo from "./childCmps/DetailShopInfo";
import DetailGoodsInfo from "./childCmps/DetailGoodsInfo";
import DetailParamInfo from "./childCmps/DetailParamInfo";
import DetailCommentInfo from "./childCmps/DetailCommentInfo";
import DetailBottomBar from "./childCmps/DetailBottomBar";

import GoodsList from "components/content/goods/GoodsList";

import Scroll from "components/common/scroll/Scroll";

import {
  getDetail,
  Goods,
  Shop,
  GoodsParam,
  getRecommend,
} from "network/detail";
import { debounce } from "common/utils";
import { itemListenerMixin, backTopMixin } from "common/mixin";

export default {
  name: "Detail",
  components: {
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    DetailBottomBar,
    Scroll,
    GoodsList,
  },
  data() {
    return {
      iid: null,
      topImages: null,
      goods: {},
      shop: {},
      detailInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      themeTopYs: [],
      getThemeTopY: null,
      currentIndex: 0,
      isShowBackTop: false,
    };
  },
  mixins: [itemListenerMixin, backTopMixin],
  created() {
    // 保存传入的 iid
    this.iid = this.$route.params.iid;
    // this.iid = this.$route.query.iid;
    // 根据 iid 请求详情数据
    getDetail(this.iid).then((res) => {
      console.log(res);
      // 获取顶部的轮播图数据
      const data = res.result;
      this.topImages = data.itemInfo.topImages;

      // 获取商品信息
      this.goods = new Goods(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );

      // 获取店铺信息
      this.shop = new Shop(data.shopInfo);

      // 获取商品的详情信息
      this.detailInfo = data.detailInfo;

      // 获取参数的信息
      this.paramInfo = new GoodsParam(
        data.itemParams.info,
        data.itemParams.rule
      );

      // 获取评论信息
      if (data.rate.cRate !== 0) {
        this.commentInfo = data.rate.list[0];
      }
      // mounted 里面也是不对的，因为在 created 里面请求数据是异步请求，在 mounted
      // 里面拿 $el 里面可能是拿不到数据的
      // updated 也是可以的
      //第一次值不对的原因: this.$refs.params.$el 压根没有渲染
      // 拿到数据之后，执行 update，所以不可能立即拿到 $el，还得在等一会
      // 第二次值不对的原因
      // 根据最新的数据，对应的 DOM 是已经被渲染出来了
      // 但是图片依然是没有加载完的
      // offsetTop 值不对的原因，都是因为图片的问题
      // this.$$nextTick(() => {
      //   this.themeTopYs = [];
      //   this.themeTopYs.push(0);
      //   this.themeTopYs.push(this.$refs.params.$el.offsetTop);
      //   this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      //   this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      // })
    });

    // 请求商品的推荐数据
    getRecommend().then((res) => {
      this.recommends = res.data.list;
    });

    // 给 themeTopYs 赋值的操作提供防抖，防抖可以提高性能
    this.getThemeTopY = debounce(() => {
      this.themeTopYs = [];
      this.themeTopYs.push(0);
      this.themeTopYs.push(this.$refs.param.$el.offsetTop);
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      // 一个非常大的值
      // this.themeTopYs.push(Number.MAX_VALUE);
    }, 100);
  },
  methods: {
    imageLoad() {
      this.$refs.scroll.refresh();

      this.getThemeTopY();
    },
    titleClick(index) {
      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 100);
    },
    contentScroll(position) {
      // 1. 获取 y 值
      const positionY = -position.y;

      // 2. positionY 和主题中值进行比较
      // [0, 1, 2, 3]
      // positionY 在 0 和 1 之间，index = 0;
      // positionY 在 1 和 2 之间，index = 1;
      // positionY 在 2 和 3 之间，index = 2;
      // hack 做法：position 在 3 和一个非常大的值之间，index = 3
      // positionY 超过 3，index = 3
      let length = this.themeTopYs.length;
      for (let i = 0; i < length; i++) {
        // 性能优化，引入 currentIndex
        if (
          this.currentIndex !== i &&
          ((i < length - 1 &&
            positionY >= this.themeTopYs[i] &&
            positionY < this.themeTopYs[i + 1]) ||
            (i === length - 1 && positionY >= this.themeTopYs[i]))
        ) {
          this.currentIndex = i;
          this.$refs.nav.currentIndex = this.currentIndex;
        }

        // 判断条件也得 length - 1，因为判断最后一个没有意义
        // if (this.currentIndex !== i && (positionY >= this.themeTopYs[i] &&
        //                                 positionY < this.themeTopYs[i + 1] )) {
        //   this.currentIndex = i;
        //   this.$refs.nav.currentIndex = this.currentIndex;
        // }
      }

      // 是否显示回到顶部
      this.listenShowBackTop(position);
    },

    addToCart() {
      const product = {};
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.iid = this.iid;

      // 2. 将商品添加到购物车里
      // this.$store.commit("addCart", product)
      this.$store.dispatch("addCart", product).then((res) => {
        this.$toast.show(res, 1500);
        // this.$toast.show();
      });
    },
  },

  destroyed() {
    this.$bus.$off("imageLoad", this.itemImageListener);
  },
};
</script>

<style scoped>
/* 下面这个东西脱离标准流，即 tabbar 会覆盖在标准流的上边，tabbar 把详情页给盖上了 */
.detail {
  /* 微调就用 relative */
  position: relative;
  z-index: 9;
  /* 详情页没有背景，相当于是透明的 */
  background-color: #fff;
  height: 100vh;
}

.detail-nav {
  position: relative;
  z-index: 9;
  background-color: #fff;
}

/* better-scroll 可以实现局部滚动 */
.content {
  height: calc(100% - 44px - 49px);
}
</style>
